package com.oocl.formV1.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ooc.formV1.service.UserService;
import com.ooc.formV1.service.impl.UserServiceImpl;
import com.oocl.formV1.pojo.User;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8"); 
		String info = "输入数据不符合格式。";
		PrintWriter writer = response.getWriter();
	
		try {
			String name = request.getParameter("name");
			double sal = Double.parseDouble(request.getParameter("sal"));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String sex = request.getParameter("sex");
			Date birth = sdf.parse(request.getParameter("birth")); //sdf.format(birth)
			
			User user = new User(name, sal, birth, sex);
			System.out.println(user.toString());
			UserService service = new UserServiceImpl();
			
			if(service.verifyFormat(user)){
				service.addUser(user);
				info = "注册成功: "+user.toString();
				List<User> users = service.findAll();
				service.showAll(users, writer);
			}
			writer.write(info);
			
		} catch (NumberFormatException e) {
			writer.write(info+"请重新注册");
			response.sendRedirect("register.html");
		} catch (ParseException e) {
			writer.write(info+"请重新注册");
			response.sendRedirect("register.html");
		}
	}

	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
